﻿using Knowledge.EF.Back.Helpers;
using Knowledge.EF.Back.Models;
using Knowledge.EF.Back.Models.DB;
using Knowledge.EF.Back.Models.Users;
using MediatR;

namespace Knowledge.EF.Back.DAL.Users
{
    public class UserLoginHandler : IRequestHandler<UserLogin, BaseResult>
    {
        private IJWTService _iJWTService = null;//注入IJWTService接口
        private readonly EFCoreContext _context; //构造一个只读的变量

        public UserLoginHandler(EFCoreContext context, IJWTService iJWTService) //创造一个构造函数 当引用_context时就会引用这函数
        {
            _context = context;
            this._iJWTService = iJWTService;
        }
        public Task<BaseResult> Handle(UserLogin request, CancellationToken cancellationToken)
        {
            try
            {
                var jsonConvertObj = JsonConvertHelper.Deserialize<User>(request.param);
                var listUser = from list in _context.Users//linq查询语句
                                 where list.username == jsonConvertObj.username && list.password == jsonConvertObj.password
                                 select list;
                if (listUser.Count() >= 1)
                {
                    string token = _iJWTService.GetToken(jsonConvertObj.username +","+jsonConvertObj.nickname);
                    return Task.FromResult(new BaseResult { Code = 200, Message = "登陆成功", Data = listUser.FirstOrDefault(), Token = token });
                }
                else
                {
                    return Task.FromResult(new BaseResult { Code = 404, Message = "用户名或密码输入有误" });
                }
            }
            catch (Exception ex)
            {
                return Task.FromResult(new BaseResult { Code = 500, Message = "服务器报错了", Data = ex });

            }
        }
    }
}
